layui.use(['tree', 'layer'], function () {
    (function ($) {
        window.Context = window.Context ? window.Context : {};

        Context.confirm = function (msg, callback) {
            layer.confirm(msg, {btn: ["取消", "确定"], skin: 'layui-layer-dark'}, null, function () {
                layer.load(0, {shade: false});
                callback && callback();
            });
        };

        Context.openHtml = function (content, options) {
            var option = $.extend({
                skin: 'layui-layer-dark',
                area: ['520px', '270px'],
                btn: ['取消', '确定'],
                content: content
            }, options);
            layer.open(option);
        };

    })(jQuery);

    (function ($) {
        $(".side-menu-list .list-item").on("click", function () {
            $(this).find("a").addClass("current");
            $(this).siblings(".list-item").find("a").removeClass("current");
        });

        // 查看我的分享
        $(".btn-do-sharelist").on("click", function () {
            Context.openHtml('<div id="share-list-box"></div>', {title: "我的分享", area: ["760px", "480px"], btn: ['关闭']});
            var layIdx = layer.load(0);
            $.get("/share_list/", {}, function (result) {
                layer.close(layIdx);
                if (result.code == 1000) {
                    $("#template-share-list").tmpl(result.data).appendTo("#share-list-box");
                    // 绑定复制链接按钮事件
                    new Clipboard(document.querySelectorAll("[data-clipboard-text]"));
                }
            });

            // 绑定取消分享按钮事件
            $("#share-list-box").on("click", "[data-share]", function () {
                var shareId = $(this).attr("data-share-id");
                var shareIds = [shareId];
                var $this = $(this);
                $.get("/share_delete/", {"share_ids": shareIds.join(",")}, function (result) {
                    if (result.code == 1000) {
                        $this.parents("tr").fadeOut("fast", function () {
                            $(this).remove();
                        });
                    }
                });
            });
        });

        // 文件选择
        $("body").on("mousedown", ".file-item", function (event) {
            $(this).toggleClass("checked");
            if (!event.ctrlKey) { // 按下Ctrl键多选
                $(this).siblings().removeClass("checked");
            }
        });

        // 全选，取消全选
        $(".check-all").on("click", function () {
            $(".file-list .file-item:not([data-new-folder])").addClass("checked");
        });

        // 切换视图
        $(".btn-file-view").on("click", function () {
            var $iconfont = $(this).find(".iconfont");
            $iconfont.hasClass("icon-menu") ?
                (function () {
                    $iconfont.removeClass("icon-menu").addClass("icon-menu1");
                    $(".file-list").removeClass("view-thumbnail");
                })() :
                (function () {
                    $iconfont.removeClass("icon-menu1").addClass("icon-menu");
                    $(".file-list").addClass("view-thumbnail");
                })();
        });

        // 绑定右键菜单时，生成菜单唯一索引
        var getIndex = function () {
            var index = new Date().getTime() + "" + Math.random();
            return index.replace(".", "");
        };

        // 下载文件
        var downloadFile = function (fileId) {
            window.open('/download/?file_id=' + fileId, '_blank');
        };

        // 分享文件
        var shareFile = function (fileId) {

        };

        // 重命名文件
        var renameFile = function (fileId) {

        };

        // 删除文件
        var deleteFile = function (fileId) {
            Context.confirm("确定要删除?", function () {
                $.post("/delete/", {"file_id": fileId}, function (result) {
                    layer.close(layer.index);
                    if (result.code == 1000) {
                        $("#file" + fileId).fadeOut("normal", function () {
                            $(this).remove();
                        });
                    } else {
                        result.msg && layer.msg(result.msg);
                    }
                });
            });
        };

        /**
         * 文件项绑定右键菜单
         */
        var initFilItemContextMenu = function (selector) {
            var i = getIndex(); // 菜单索引
            selector = typeof selector == "string" ? document.querySelector(selector) : selector;
            var fileId = $(selector).attr("data-file-id");
            ContextMenu.bind(selector, [
                {
                    name: "<span class='iconfont icon-download text-primary'></span> 下载",
                    id: "webcontextmenu-rename-" + i,
                    callback: function () {
                        downloadFile(fileId);
                    }
                }, {
                    name: "<span class='iconfont icon-share text-primary'></span> 分享",
                    id: "webcontextmenu-share-" + i,
                    callback: function () {
                        shareFile(fileId);
                    }
                }, {
                    name: "<span class='iconfont icon-rename text-primary'></span> 重命名",
                    id: "webcontextmenu-rename-" + i,
                    callback: function () {
                        renameFile(fileId);
                    }
                }, {
                    name: "<span class='iconfont icon-trash text-danger'></span> 删除",
                    id: "webcontextmenu-delete-" + i,
                    callback: function () {
                        deleteFile(fileId);
                    }
                }
            ]);
        };

        // 绑定右键菜单
        $(".file-item").each(function () {
            initFilItemContextMenu(this);
        });

        /**
         * 设置当前所在目录
         */
        var setCurrentFolder = function (folderId) {
            $("#data_file_parent").val(folderId);
            // 更改上传的目录
            uploader.options.formData.file_parent = folderId;
        };

        /**
         * 设置前一个目录
         */
        var setPrevFolder = function (folderId) {
            $("#data_file_prev").val(folderId);
        };

        /**
         * 获取当前所在目录
         */
        var getCurrentFolder = function () {
            return $("#data_file_parent").val();
        };

        /**
         * 填充文件列表
         */
        var fillFileList = function (data) {
            $(".file-list").empty();
            $("#template-file-list").tmpl(data).appendTo(".file-list");
            $(".file-list .file-item").each(function () {
                initFilItemContextMenu(this);
            });
        };

        /**
         * 从后台获取文件列表
         */
        var loadFileListFromServer = function (params, parentId) {
            layer.load(0);
            $.get("/list_file/", params, function (result) {
                layer.close(layer.index);
                if (result.code == 1000) {
                    fillFileList(result.data);
                    setPrevFolder(result.data.prev);
                    setCurrentFolder(parentId);
                }
            });
        };

        // 搜索文件
        $("#btn-do-search").on("click", function () {
            $("#fm-search").submit();
        });
        $("#fm-search").on("submit", function () {
            var keywords = $(this).find("[name=keywords]").val().trim();
            if (keywords) {
                layer.load(0);
                loadFileListFromServer({"keyword": keywords}, "");
            }
        });

        // 根目录
        $(".btn-do-listallfile").on("click", function () {
            loadFileListFromServer({"file_parent": ""}, "")
        });

        // 返回前一个目录
        $(".btn-do-prev").on("click", function () {
            var prevFolderId = $("#data_file_prev").val().trim();
            if (prevFolderId != getCurrentFolder()) {
                loadFileListFromServer({"file_parent": prevFolderId}, prevFolderId);
            }
        });

        // 新建文件夹
        $("#btn-do-newfolder").on("click", function () {
            var $fileList = $(".file-list");
            var $newFolder = $fileList.find("[data-new-folder]");
            if (!$newFolder.length) {
                $fileList.prepend($("#template-new-folder").html()).find("[data-new-folder] input").focus();
            } else {
                $newFolder.find("input").focus();
            }
        });

        $(".file-list")
            .on("click", "#btn-new-folder-cancel", function () {
                $("[data-new-folder]").fadeOut('fast', function () {
                    $(this).remove();
                });
            })
            .on("click", "[data-file-type='1'] .file-name-text", function (event) {
                if (event.ctrlKey) {
                    return;
                }
                // 点击文件夹,进入到文件夹
                var parentId = $(this).parents("[data-file-type='1']").attr("data-file-id");
                loadFileListFromServer({"file_parent": parentId}, parentId);
            })
            .on("submit", "#fm-new-folder", function () {
                // 请求服务器新建文件夹
                layer.load(0);
                $.post(
                    "/folder_add/",
                    {
                        "folder_name": $("#new_folder_name").val(),
                        "folder_parent": getCurrentFolder()
                    },
                    function (result) {
                        layer.close(layer.index);
                        if (result.code == 1000) {
                            $("#template-file-item").tmpl(result.data).prependTo(".file-list");
                            initFilItemContextMenu("#file" + result.data.id);
                            $("[data-new-folder]").remove();
                        } else {
                            result.msg && layer.msg(result.msg)
                        }
                    }
                );
            });

        // 获取选择的文件项的ID
        var getCheckedFiles = function () {
            var ids = [];
            $(".file-list .file-item:not([data-new-folder])").each(function () {
                if ($(this).hasClass("checked")) {
                    var id = $(this).attr("data-file-id");
                    id && ids.push(id);
                }
            });
            return ids;
        };

        // 分享选中文件
        var shareFile = function (fileIds, isEncrypt) {
            var layIndex = layer.load(0);
            $.post("/share/", {
                "file_ids": typeof fileIds === 'string' ? fileIds : fileIds.join(","),
                "is_encrypt": isEncrypt
            }, function (result) {
                layer.close(layIndex);
                if (result.code == 1000) {
                    $("#share-result-url").val(result.data.share_url);
                    $("#share-result-pwd").val(result.data.password);
                    $(".share-box .share-buttons button").attr("disabled", "disabled");
                    $(".share-box .share-result-inputs").show();
                    if (!isEncrypt) {
                        $(".share-box .share-result-inputs .form-group:eq(1)").hide();
                    }
                }
            });
        };

        $("#btn-do-share").on("click", function () {
            var fileIds = getCheckedFiles();
            if (!fileIds.length) {
                return;
            }
            Context.openHtml($("#template-share-box").html(), {title: "分享文件"});
            $("#btn-share-public").on("click", function () {
                shareFile(fileIds, 0);
            });
            $("#btn-share-primary").on("click", function () {
                shareFile(fileIds, 1);
            });
        });

        // 删除选中文件
        $("#btn-do-delete").on("click", function () {
            var fileIds = getCheckedFiles();
            fileIds.length &&
            Context.confirm("确定要删除选中的文件?", function () {
                layer.load(0);
                $.post("/delete_files/", {"file_ids": fileIds.join(",")}, function (result) {
                    layer.close(layer.index);
                    if (result.code == 1000) {
                        $.each(fileIds, function (i, e) {
                            $("#file" + e).fadeOut("normal", function () {
                                $(this).remove();
                            });
                        });
                    }
                });
            });
        });

        // 下载选中文件
        $("#btn-do-download").on("click", function () {
            var fileIds = getCheckedFiles();

        });

        // 移动文件
        $("body").on("mouseup", ".layui-tree a", function () {
            $("#file-move-tree a").css("background-color", "transparent");
            $(this).css("background-color", "#f90");
        });
        $("#btn-do-moveto").on("click", function () {
            var fileIds = getCheckedFiles();
            if (!fileIds.length) {
                return;
            }
            Context.openHtml('<div id="file-move-tree"></div>', {
                title: "移动文件", area: ["520px", "420px"], btn2: function () {
                    var layIndex = layer.load(0);
                    $.post("/file_move/", {
                        "file_ids": fileIds.join(","),
                        "target": sessionStorage.getItem("currentMoveTargetFolder")
                    }, function (result) {
                        layer.close(layIndex);
                        if (result.code == 1000) {
                            $.each(fileIds, function (i, e) {
                                $("#file" + e).fadeOut("fast", function () {
                                    $(this).remove();
                                });
                            });
                        } else {
                            layer.msg(result.msg);
                        }
                    });
                }
            });
            var options = {
                elem: "#file-move-tree",
                click: function (item) {
                    sessionStorage.setItem("currentMoveTargetFolder", item.id);
                    if (item.loaded === false) {
                        var layIndex = layer.load(0);
                        $.get("/child_folder_get/", {"parent": item.id}, function (result) {
                            layer.close(layIndex);
                            if (result.code == 1000) {
                                item.loaded = true;
                                var children = [];
                                $.each(result.data, function (i, folder) {
                                    children.push({
                                        name: folder.file_name,
                                        id: folder.id,
                                        loaded: false,
                                        spread: true
                                    });
                                });
                                item.children = children;
                                $("#file-move-tree").empty();
                                layui.tree(options);
                            }
                        });
                    }
                },
                nodes: [{
                    name: "根目录",
                    id: "",
                    spread: true,
                    loaded: false
                }]
            };
            layui.tree(options);
        });


        //初始化Web Uploader
        var uploader = WebUploader.create({
            auto: true, // 自动上传
            swf: "/static/webuploader/Uploader.swf",
            server: "/ajax_upload/", // 服务器地址
            // 内部根据当前运行是创建，可能是input元素，也可能是flash.
            pick: "#filePicker",
            formData: {
                csrfmiddlewaretoken: $(".my-upload").attr("data-csrf-token"),
                file_parent: getCurrentFolder()
            },
            /*
            // 文件类型过滤
            accept: {
                title: "Image",
                extensions: "gif,jpg,jpeg,bmp,png",
                mimeTypes: "image/*"
            }
            */
        });

        uploader.on("fileQueued", function (file) {
            $(".my-upload").removeClass("minimize closed");
            var item =
                '<li class="list-group-item" id="' + file.id + '">' +
                '	<span class="file-name">' + file.name + '</span>' +
                '	<span class="file-size">' + UploaderUtils.calcFileLength(file.size) + '</span>' +
                '	<span class="upload-percent">0%</span>' +
                '	<span class="file-state"><i class="glyphicon glyphicon-refresh"></i></span>' +
                '	<span class="upload-progress"></span>' +
                '</li>';
            $(".my-upload .list-group").append($(item));
        });

        uploader.on("uploadProgress", function (file, percentage) {
            var $li = $("#" + file.id),
                $percent = $li.find("span.upload-progress");
            var percent = parseInt(percentage * 100) + "%";
            $percent.css("width", percent);
            $li.find("span.upload-percent").text(percent);
        });
        uploader.on("uploadSuccess", function (file, response) {
            $("#" + file.id).find(".file-state i.glyphicon").removeClass("glyphicon-refresh").addClass("glyphicon-ok");
            // 上传成功
            if (response.code == 1000) {
                $("#template-file-item").tmpl(response.data).prependTo(".file-list");
                initFilItemContextMenu("#file" + response.data.id);
            }
        });
        // 文件上传失败，显示上传出错。
        uploader.on("uploadError", function (file) {
            $("#" + file.id).find(".file-state i.glyphicon")
                .removeClass("glyphicon-refresh").addClass("glyphicon-remove");
        });
        // init scrollbar
        $(".my-upload .list-group").niceScroll({
            styler: "fb",
            cursorwidth: '6',
            cursorborderradius: '10px',
            background: '#FFFFFF',
            spacebarenabled: false,
            cursorborder: '0'
        });
        // end init webuploader

        // 右下角上传文件对话框切换
        $(".btn-close-myupload").on("click", function (event) {
            $(".my-upload").addClass("closed").removeClass("minimize");
            event.stopPropagation();
        });
        $("body").on("click", ".my-upload.closed", function (event) {
            $(this).removeClass("closed");
            event.stopPropagation();
        });
        $(".btn-minimize-myupload").on("click", function (event) {
            $(".my-upload").toggleClass("minimize");
            event.stopPropagation();
        });

    })(jQuery);
});